package com.starblink.search.category.ui.newlist

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.rocketreserver.FetchSaleZoneForegroundCategoryV2Query
import com.starblink.rocketreserver.GetSubFrontCategoriesByCategoryIdQuery
import com.starblink.rocketreserver.fragment.CategoryD
import com.starblink.rocketreserver.fragment.CategoryF
import com.starblink.rocketreserver.type.SaleZoneCategoryReq
import com.starblink.search.category.data.CategoryModel
import com.starblink.search.category.data.CategoryWithParentId
import kotlinx.coroutines.launch

class CategoryChildrenVM : BaseViewModel() {

    val contentList = arrayListOf<CategoryModel>()
    val contentLD = MutableLiveData<MutableList<CategoryWithParentId>>(mutableListOf())

    val isFirstExpand = false


    internal fun loadIniData() {
        viewModelScope.launch {
            var oneCateList: ArrayList<CategoryWithParentId>? = null

            // ！=0 为非sales Zone的数据
            if (CategoryConfig.getCategoryId() != "0") {
                val result0 = SkGqlClient.skQuery(
                    GetSubFrontCategoriesByCategoryIdQuery(CategoryConfig.getCategoryId()),
                    showDefaultLoading = true
                )?.data?.getSubFrontCategoriesByCategoryId
                result0?.forEach {
                    it.let {
                        if (oneCateList == null) {
                            oneCateList = arrayListOf()
                        }
                        oneCateList?.add(
                            CategoryWithParentId(
                                CategoryConfig.getCategoryId(),
                                it.categoryD
                            )
                        )
                    }
                }
            } else {
                //  =0 请求 sales Zone的数据
                val result1 = SkGqlClient.skQuery(
                    FetchSaleZoneForegroundCategoryV2Query(
                        params = SaleZoneCategoryReq(
                            level = Optional.present(1),
                        )
                    )
                )?.data?.fetchSaleZoneForegroundCategoryV2
                result1?.forEach { it ->
                    it?.let {
                        if (oneCateList == null) {
                            oneCateList = arrayListOf()
                        }
                        oneCateList?.add(
                            CategoryWithParentId(
                                CategoryConfig.getCategoryId(),
                                it.categoryD
                            )
                        )
                    }
                }
            }
            Log.e("CategoryChildren", "---00000-$oneCateList")
            contentLD.value?.clear()
            if (!oneCateList.isNullOrEmpty() && oneCateList!!.size > 0) {
                if (CategoryConfig.getCategoryId() != "0") {
                    oneCateList!![0].expand = true
                }
                contentLD.value?.addAll(oneCateList!!)
                contentLD.value = contentLD.value
                getSalesZoneLevel3ById(
                    isInit = true,
                    oneCateList!![0].category.id,
                    0,
                    false
                )
            }
        }
    }


    fun getSalesZoneLevel3ById(
        isInit: Boolean,
        frontCategoryId: Any?,
        clickPosition: Int,
        clicked: Boolean
    ) {
        var threeCateList: ArrayList<CategoryD> = arrayListOf()
        var childrenData: ArrayList<CategoryD.Child> = ArrayList()
        viewModelScope.launch {
            val result1 = SkGqlClient.skQuery(
                FetchSaleZoneForegroundCategoryV2Query(
                    params = SaleZoneCategoryReq(
                        level = Optional.present(3),
                        firstLevelFrontCategoryId = Optional.present(frontCategoryId)
                    ),
                ),
                showDefaultLoading = !isInit
            )?.data?.fetchSaleZoneForegroundCategoryV2
            result1?.forEach {
                it?.let {
                    threeCateList.add(it.categoryD)
                }
            }
            threeCateList.forEach {
                childrenData.add(
                    CategoryD.Child(
                        __typename = it.hashCode().toString(),
                        categoryF = CategoryF(
                            id = it.id,
                            name = it.name,
                            level = it.level,
                            imageUrl = it.imageUrl,
                            littleImageUrl = it.littleImageUrl,
                            existsLowerLevel = it.existsLowerLevel,
                            iconUrl = it.iconUrl,
                            traceId = it.traceId,
                            traceInfo = it.traceInfo,
                            highestDiscountInfo = it.highestDiscountInfo,
                        )
                    )
                )
            }

            if (childrenData.size > 0) {
                ApolloValSetExt.setApolloVal<CategoryD>(
                    contentLD.value!![clickPosition].category,
                    "children",
                    childrenData
                )
//                contentLD.value!!.forEach { item ->
//                    item.expand = false
//                }
                contentLD.value!![clickPosition].expand = !clicked
                contentLD.value = contentLD.value
            }
        }

    }


    fun changeData(list: List<CategoryWithParentId>) {
        contentLD.value?.clear()
        contentLD.value?.addAll(list)
        contentLD.value = contentLD.value
    }

}